<?php

if (!isset($_GET['id'])) {
    $topic_length = strlen(sanitize($_POST['topic']));
    if ($topic_length > $CONF['MAX_TOPIC_LENGTH'])
        $error = "Topic is too long. Max is {$CONF['MAX_TOPIC_LENGTH']} characters.";
    if ($topic_length < $CONF['MIN_TOPIC_LENGTH'])
        $error = "Topic is too short. Min is {$CONF['MIN_TOPIC_LENGTH']} characters.";

    $tag = sanitize($_POST['tag']);
    if (!in_array($tag, $CONF['BBS_TAGS'])) {
        $error = "The tag \"{$tag}\" doesn't exist.";
    }
}

$name_length = strlen(sanitize($_POST['name']));
if ($name_length > $CONF['MAX_NAME_LENGTH'])
    $error = "Name is too long. Max is {$CONF['MAX_NAME_LENGTH']} characters.";
if (empty($name_length))
    $_POST['name'] = "Anonymous";

$email_length = strlen(sanitize($_POST['email']));
if ($email_length > $CONF['MAX_EMAIL_LENGTH'])
    $error = "Email is too long. Max is {$CONF['MAX_EMAIL_LENGTH']} characters.";

$message_length = strlen(sanitize($_POST['message']));
if ($message_length > $CONF['MAX_MESSAGE_LENGTH'])
    $error = "Message is too long. Max is {$CONF['MAX_MESSAGE_LENGTH']} characters.";
if ($message_length < $CONF['MIN_MESSAGE_LENGTH'])
    $error = "Message is too short. Min is {$CONF['MIN_MESSAGE_LENGTH']} characters.";


if ($_POST['pulcinella'] !== "43aa950ba2689dd76e55e2596163a43b") {
    $error = "Don't be such a bot, pal.";
}

// Check if there are enormously long word
function contains_sesquipedalian(string $input, int $max_length): bool {
    $words = preg_split('/\s+/', $input);
    foreach ($words as $word) {
        if (strlen($word) > $max_length) {
            return true;
        }
    }
    return false;
}

if ($CONF['MAX_WORD_LENGTH'] > 0) {
    foreach ($_POST as $input) {
        if (contains_sesquipedalian($input, $CONF['MAX_WORD_LENGTH'])) {
            $error = "Some of the words is enourmously long. Max is {$CONF['MAX_WORD_LENGTH']} characters.";
        }
    }
}

// Render error if any
if (isset($error)) {
    include("./templates/header.php");
    echo "<hr/>";
    echo "<p style=\"color: red;\">" . $error . "</p>";
    echo "<nav class=\"return-nav\"><a href=\"/index.php\">Return</a></nav>";
    include("./templates/footer.html");
    exit();
}

?>
